programming4us
           
 
 
Windows Phone

Developing for Windows Phone and Xbox Live : Multiplayer Games (part 3) - Creating a Network Session

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
7/18/2011 5:46:04 PM

Creating a Network Session

Although your main menu has text that says, “press A to create a session,” pressing the button does not do anything. To change this, add the following lines of code to the MainMenuUpdate method:

// Create a new session
if (ButtonPressed(Buttons.A))
gameState = GameState.CreateSession;

This causes oyur game to change to the CreateSession state after the user presses the A button.

Because the game is in CreateSession state, add to the switch statements in the Update and Draw methods so they know what to do while you are in this state.

In the game’s Draw method, add the following to the switch statement:

case GameState.CreateSession:
CreateSessionDraw();
break;

The CreateSessionDraw handles drawing the menu screen when the game is in the CreateSession state. Add the CreateSessionDraw method to your game.

// Draw method for the CreateSession GameState
private void CreateSessionDraw()
{
spriteBatch.Begin();
spriteBatch.DrawString(spriteFont, "CREATE SESSION",
new Vector2(10, 10), Color.White);
spriteBatch.DrawString(spriteFont, "Deathmatch - Press A",
new Vector2(10, 50), Color.White);
spriteBatch.DrawString(spriteFont, "CaptureTheFlag - Press B",
new Vector2(10, 90), Color.White);
spriteBatch.DrawString(spriteFont, "FreeForAll - Press X",
new Vector2(10, 130), Color.White);
spriteBatch.DrawString(spriteFont, "Exit - Press Back",
new Vector2(10, 170), Color.White);
spriteBatch.End();
}

In the game’s Update method, add the following lines of code to the switch statement:

case GameState.CreateSession:
CreateSessionUpdate();
break;

While the game is in the CreateSession state, call the CreateSessionUpdate method to run the update logic for the state. Add the following method to your Game class:

// Update method for the create session method
private void CreateSessionUpdate()
{
// Move back to the main menu
if (ButtonPressed(Buttons.Back))
gameState = GameState.MainMenu;
// Create a new session with different
// using different values for GameType
else if (ButtonPressed(Buttons.A))
CreateSession(GameType.Deathmatch);
else if (ButtonPressed(Buttons.B))
CreateSession(GameType.CaptureTheFlag);
else if (ButtonPressed(Buttons.X))
CreateSession(GameType.FreeForAll);
}

CreateSessionUpdate checks for button presses to create different game types by calling the CreateSession method, which you create in a moment. The GameType is an enumeration that you create for the game. Add the following enumeration to your game:

public enum GameType { Deathmatch, CaptureTheFlag, FreeForAll };

Before you implement CreateSession, you need an additional enumeration and some fields added to your game. Add the following enumeration to your game:

public enum SessionProperties { GameType, MapLevel, OtherCustomProperty };

When you create a session, you can provide a number of integer values that will define what type of session to create. A helpful way to keep track of integer values is to use an enumeration. In this case, create SessionProperties, which defines three types of properties.

You also need to add a member variable to store the NetworkSession. The NetworkSession object is what you use to manage the active session and to send and receive data over the session. You can think of a session as the connection of your machine with the other machines. There are times that gamers join and times where they leave, but there is always a host to the session that controls the current state of the session. If the host leaves the session, the session is over unless host migration is turned on. In that case, a new host is selected. Add the following member variable to your game:

// The network session for the game
NetworkSession networkSession;

Now you can create the CreateSession method that creates a new session given a GameType. The GameType is passed in depending on the selection the player has made from the create session menu screen.

// Createa a new NetworkSession
private void CreateSession(GameType gameType)
{
// If we have an existing network session we need to dispose of it
if (networkSession != null && !networkSession.IsDisposed)
networkSession.Dispose();

// Create the NetworkSessionProperties to use for the session
// Other players will use these to search for a session
NetworkSessionProperties sessionProperties = new NetworkSessionProperties();
sessionProperties[(int)SessionProperties.GameType] = (int)gameType;
sessionProperties[(int)SessionProperties.MapLevel] = 0;
sessionProperties[(int)SessionProperties.OtherCustomProperty] = 42;

// Create the NetworkSession NetworkSessionType of SystemLink
networkSession = NetworkSession.Create(NetworkSessionType.SystemLink, 1, 4, 0,
sessionProperties);
networkSession.AllowJoinInProgress = true;

// Register for NetworkSession events
networkSession.GameStarted +=
new EventHandler<GameStartedEventArgs>(networkSession_GameStarted);
networkSession.GameEnded +=
new EventHandler<GameEndedEventArgs>(networkSession_GameEnded);
networkSession.GamerJoined +=
new EventHandler<GamerJoinedEventArgs>(networkSession_GamerJoined);
networkSession.GamerLeft +=
new EventHandler<GamerLeftEventArgs>(networkSession_GamerLeft);
networkSession.SessionEnded +=
new
EventHandler<NetworkSessionEndedEventArgs>(networkSession_SessionEnded);

// Move the game into the GameLobby state
gameState = GameState.GameLobby;
}


Before you create the session, check whether you need to dispose of an already existing session.

When you create a session, you provide a set of NetworkSessionProperties. These properties define how the session is used. For example, your game might have multiple types of multiplayer games, different levels, or other values that define what is happening in the session. These values are important because they are used when you search for available sessions. The values can also be displayed in the search results when players are looking for a session to join.

The different values of the SessionProperties enumeration are used to index into the NetworkSessionProperties. We give some simple values for the MapLevel and OtherCustomProperty just to show you how this is done. If this was a real game, you would use the player’s map selection and other logic to drive these values.

Now you are ready to create the NetworkSession. The Create method takes a number of parameters and has a few overloads. The first value is the NetworkSessionType to create. As the name of the enumeration implies, this is the type of network session to create. There are four main types of sessions.

The first type of NetworkSessionType is Local. As the name implies, the NetworkSession is local only to a single machine. This is useful if you create a networked game but then want to use the same networking code for your split screen game.

SystemLink is the type of NetworkSessionType that you are using in this sample and is most likely what you will use while in development. It enables multiple machines that are on the same local area network to connect to each other.

PlayerMatch and Ranked are Xbox LIVE sessions that enable gamers to play across the world together.

The second parameter to the NetworkSession.Create method is the number of local gamers that participate in the session. Your game can allow for multiple players on the same console to join other players in a networked game. When you join a session, you and any other local gamers take up multiple spots in the session. In the sample, we set this value to 1 for just a single local user.

The third parameter is the max number of gamers for the entire session. XNA games can support up to 31 maximum players per session. Although 31 players are possible, determine what makes sense for your game and what type of performance you get with multiple players in the session.

The fourth parameter is the amount of private slots. A private slot is one that can be filled only by an invite from a player in the session. This is helpful for times where players are trying to have a game with their friends and don’t want other players to join.

The final parameter is the NetworkSessionProperties that you created earlier. The Create method returns to you a new NetworkSession.

Note

NetworkSession.Create can block for a number of frames. XNA provides asynchronous BeginCreate and EndCreate methods to prevent your game from skipping frames.


After creating the NetworkSession, set the AllowJoinInProgress to true. This property enables players joining the session to do so even if the game has already started.

Now that the new NetworkSession is created, register for a number of helpful events that will occur during the lifespan of the NetworkSession.

The GameStarted and GameEnded events fire when the session starts and ends a game. A game is different than a session. A session is the connection of the players while a game represents a play session. For examples, you and your friends can stay in one session while you play multiple games that start and finish over and over again. These events are raised when the NetworkSession.StartGame and NetworkSession.EndGame methods are called. Add the following two event handlers to your game:

// Event handler for the NetworkSession.GameStarted event
// This event is fired when the host call NetworkSession.StartGame
void networkSession_GameStarted(object sender, GameStartedEventArgs e)
{
gameMessages.Add(new DisplayMessage("Game Started", TimeSpan.FromSeconds(2)));
// Move the game into the PlayingGame state
gameState = GameState.PlayingGame;
}

// Event handler for the NetworkSession.GameEnded event
// This event is fired when the host call NetworkSession.EndGame
void networkSession_GameEnded(object sender, GameEndedEventArgs e)
{
gameMessages.Add(new DisplayMessage("Game Ended", TimeSpan.FromSeconds(2)));
// Move the game into the GameLobby state
gameState = GameState.GameLobby;
}

When the game starts or ends, print a message and set the next GameState.

The GamerJoined and GamerLeft events fire when a gamer joins or leaves the session. Even the host gets the GamerJoined event. Add the following two event handlers to your game:

// Event handler for the NetworkSession.GamerJoined event
// This event is fired when someone joins the session
// This event will fire even for local gamers
void networkSession_GamerJoined(object sender, GamerJoinedEventArgs e)
{
gameMessages.Add(new DisplayMessage("Gamer Joined: " + e.Gamer.Gamertag,
TimeSpan.FromSeconds(2)));

// Add a new GameObject that we will use to store game state for the player
e.Gamer.Tag = new GameObject(new Vector2(random.Next(100, 1000),
random.Next(100, 600)));
}

// Event handler for the NetworkSession.GamerLeft event
// This event is fired when a player leaves the session
void networkSession_GamerLeft(object sender, GamerLeftEventArgs e)
{
gameMessages.Add(new DisplayMessage("Gamer Left: " + e.Gamer.Gamertag,
TimeSpan.FromSeconds(2)));
}


For both the GamerJoined and GamerLeft events, you print a message with the Gamertag. The GamerJoined handler also adds a new GameObject to the TagGamer. The Tag property enables you to store any type of object on an instance of a Gamer. You use a simple class called GameObject, which stores the current position of the player. In your game, you can store all of the players’ current state in this type. property of the

Define the GameObject class in your game using the following code:

// Each gamer in the session will have their own GameObject
public class GameObject
{
public Vector2 Position
{ get; set; }

public GameObject(Vector2 position)
{
Position = position;
}
}

The final event SessionEnded is fired when a player leaves the session. Add the following event handler to your game:

// Event handler for the NetworkSession.SessionEnded event
// This event is fired when your connection to the NetworkSession is ended
void networkSession_SessionEnded(object sender, NetworkSessionEndedEventArgs e)
{
gameMessages.Add(new DisplayMessage("Session Ended: " + e.EndReason.ToString(),
TimeSpan.FromSeconds(2)));

// Since we have disconnected we clean up the NetworkSession
if (networkSession != null && !networkSession.IsDisposed)
networkSession.Dispose();

// Move the game into the MainMenu state
gameState = GameState.MainMenu;
}


After the session ends, dispose of the NetworkSession and set the gameState to go back to the MainMenu.

After the CreateSession has completed, you are in the GameLobby state waiting for others to join and for the game to start.

Running the game now should enable you to go to the create session screen and see something similar to Figure 5.

Figure 5. Create session menu screen

The NetworkSession needs to be updated to allow for data to be sent and received to all of the players in the session. To do this, call NetworkSession.Update. In the game’s Update method, add the following code:

// Update the network session we need to check to
// see if it is disposed since calling Update on
// a disposed NetworkSession will throw an exception
if (networkSession != null && !networkSession.IsDisposed)
networkSession.Update();

If the session is not null and has not been disposed, call the Update method.

Other -----------------
- User Interface : Using the ApplicationBar Control
- User Interface : Creating an Animated Splash Screen
- Windows Phone 7 Game Development : The World of 3D Graphics - Vertex and Index Buffers
- Windows Phone 7 Game Development : The World of 3D Graphics - Hidden Surface Culling
- Windows Phone 7 Game Development : The World of 3D Graphics - The Depth Buffer
- Windows Phone 7 Game Development : The World of 3D Graphics - Rendering 3D Objects
- Windows Phone 7 Game Development : The World of 3D Graphics - Perspective Projection
- Developing for Windows Phone and Xbox Live : Let the 3D Rendering Start
- Developing for Windows Phone and Xbox Live : Reach and HiDef Graphics Profiles
- Developing for Windows Phone and Xbox Live : Graphics Pipeline
- Developing for Windows Phone and Xbox Live : Graphics Pipeline
- Programming Windows Phone 7 : Elements and Properties - More on Images
- Programming Windows Phone 7 : TextBlock Properties and Inlines
- Programming Windows Phone 7 : The Phone’s Photo Library
- Programming Windows Phone 7 : Capturing from the Camera
- Windows Phone 7 : Loading Local Bitmaps from Code
- Windows Phone 7 : Image and ImageSource
- Windows Phone 7 : Images Via the Web
- Windows Phone 7 : Customizing Your E-Mail Signature
- Windows Phone 7 : Managing Mail Folders
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us